﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using System.Xml;
using System.Net.Mail;

/// <summary>
/// Common 的摘要说明
/// </summary>
public class Common
{
    public Common()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    protected static string strJsAlert = string.Empty;
    public static readonly string Key = "西宝DEC密匙";

    #region 判断文件夹是否存在 如果不存在，则创建
    /// <summary>
    /// 判断文件夹是否存在 如果不存在，则创建
    /// </summary>
    /// <param name="path">相对路径</param>
    public static string DirIsExists(string path)
    {
        try
        {
            path = HttpContext.Current.Server.MapPath(path);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            Directory.CreateDirectory(path);
            return path;
        }
        catch
        {
            throw;
        }
    }
    #endregion

    #region JS对话框

    /// <summary>
    /// 向页面注册简单的Alert对话框（仅弹出对话框）
    /// </summary>
    /// <param name="page"></param>
    /// <param name="text"></param>
    public static void Alert(Page page, string text)
    {
        page.ClientScript.RegisterStartupScript(typeof(Page), "jsAlert",
               "alert('" + text + "');", true);
    }
    /// <summary>
    /// 向页面注册简单的Alert对话框（仅弹出对话框）
    /// </summary>
    /// <param name="page"></param>
    /// <param name="text"></param>
    public static void AlertRefresh(Page page, string text)
    {
        page.ClientScript.RegisterStartupScript(typeof(Page), "jsAlert",
               "alert('" + text + "');window.location.href=location.href;", true);
    }

    /// <summary>
    /// 向页面注册简单的Alert对话框,并跳转到指定页面
    /// </summary>
    /// <param name="page">页面对象引用</param>
    /// <param name="text">对话框内容</param>
    /// <param name="text">需跳转到得页面</param>
    public static void Alert(Page page, string text, string Location)
    {
        page.ClientScript.RegisterStartupScript(typeof(Page), "jsAlert",
               "alert('" + text + "');window.location.href='" + Location + "'", true);
    }

    /// <summary>
    /// 向页面注册Alert对话框（用于Edit页面）
    /// </summary>
    /// <param name="page">页面引用</param>
    /// <param name="TextFlag">操作成功标识 1为成功，0为失败</param>
    /// <param name="Flag">标识，0为新增，1为修改</param>
    public static void Alert(Page page, int TextFlag, int Flag)
    {
        //新增
        if (Flag == 0)
        {
            strJsAlert = TextFlag == 1 ? "新增成功" : "新增失败";
        }
        else if (Flag == 1)//修改
        {
            strJsAlert = TextFlag == 1 ? "修改成功" : "修改失败";
        }
        page.ClientScript.RegisterStartupScript(typeof(Page), "jsAlert1",
            "alert('" + strJsAlert + "');", true);
    }

    /// <summary>
    /// 向页面注册Alert对话框后，并跳转到指定页面（用于Edit页面）
    /// </summary>
    /// <param name="page">页面引用</param>
    /// <param name="TextFlag">操作成功标识 1为成功，0为失败</param>
    /// <param name="Flag">标识，0为新增，1为修改</param>
    /// <param name="Location">需跳转到URL</param>
    public static void Alert(Page page, int TextFlag, int Flag, string Location)
    {
        //新增
        if (Flag == 0)
        {
            strJsAlert = TextFlag == 1 ? "新增成功" : "新增失败";
        }
        else if (Flag == 1)//修改
        {
            strJsAlert = TextFlag == 1 ? "修改成功" : "修改失败";
        }
        page.ClientScript.RegisterStartupScript(typeof(Page), "jsAlert1",
                "alert('" + strJsAlert + "');window.location='" + Location + "';", true);
    }
    #endregion

    #region 删除指定名称Cookie
    public static void RemoveCookie(string cookieName)
    {
        HttpCookie hc = HttpContext.Current.Request.Cookies[cookieName]; //XXXX为Cookie的名字
        if (hc != null)
            hc.Expires = DateTime.Now.AddDays(-1); //设置过期时间为过去的某个时间
        HttpContext.Current.Response.Cookies.Add(hc); //覆盖客户端的同名Cookie
    }
    #endregion

    #region 将制定键名Cookie对象序列化
    /// <summary>
    /// 二进制对象序列化
    /// </summary>
    /// <param name="obj">对象</param>
    /// <returns>返回二进制字符串</returns>
    public static string BinarySerialize(object obj, string cookiename)
    {
        BinaryFormatter bf = new BinaryFormatter();  //声明一个序列化类
        MemoryStream ms = new MemoryStream();  //声明一个内存流
        bf.Serialize(ms, obj);  //执行序列化操作
        byte[] result = new byte[ms.Length];
        result = ms.ToArray();
        string temp = System.Convert.ToBase64String(result);
        temp = Encrypt(temp, "nmf#gfs*fsa@Vhts");
        HttpCookie cookie = new HttpCookie(cookiename);
        //cookie.Expires = DateTime.Now.AddHours(2);
        //cookie.Value = temp;       
        cookie.Values.Add("key", "zdcb");
        cookie.Values.Add("val", temp);
        if (HttpContext.Current.Response.Cookies[cookiename] == null)
        {
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        else
        {
            HttpContext.Current.Response.Cookies.Set(cookie);
        }
        ms.Flush();
        ms.Close();
        return temp;
    }
    #endregion

    #region 将制定键名Cookie对象反序列化
    /// <summary>
    /// 二进制对象反序列化
    /// </summary>
    /// <param name="str">二进制字符串</param>
    /// <returns>反选Object对象</returns>
    public static Object BinaryDeserialize(string cookiename)
    {
        if (HttpContext.Current.Request.Cookies[cookiename] != null)
        {
            try
            {
                string temp = HttpContext.Current.Request.Cookies[cookiename].Values["val"];
                temp = Decrypt(temp, "nmf#gfs*fsa@Vhts");
                byte[] b = System.Convert.FromBase64String(temp);  //将得到的字符串根据相同的编码格式分成字节数组
                MemoryStream msb = new MemoryStream(b, 0, b.Length);  //从字节数组中得到内存流
                BinaryFormatter bfb = new BinaryFormatter();
                return bfb.Deserialize(msb);  //返回Object对象
            }
            catch (Exception)
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }
    #endregion

    #region 原DEC 加密过程

    /// <summary>
    /// DEC 加密过程
    /// </summary>
    /// <param name="strValue">被加密的字符串</param> 
    /// <returns>加密后的字符串</returns>
    public static string Encrypt(string strValue, string sKey)
    {
        if (sKey == null)
        {
            sKey = Key;
        }
        //访问数据加密标准(DES)算法的加密服务提供程序 (CSP) 版本的包装对象
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.Key = ASCIIEncoding.ASCII.GetBytes(sKey.Substring(0, 8));　//建立加密对象的密钥和偏移量
        des.IV = ASCIIEncoding.ASCII.GetBytes(sKey.Insert(0, "w").Substring(0, 8));　 //原文使用ASCIIEncoding.ASCII方法的GetBytes方法

        byte[] inputByteArray = Encoding.Default.GetBytes(strValue);//把字符串放到byte数组中

        MemoryStream ms = new MemoryStream();//创建其支持存储区为内存的流　
        //定义将数据流链接到加密转换的流
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        //上面已经完成了把加密后的结果放到内存中去

        StringBuilder ret = new StringBuilder();
        foreach (byte b in ms.ToArray())
        {
            ret.AppendFormat("{0:X2}", b);
        }
        ret.ToString();
        return ret.ToString();
    }
    #endregion

    #region  原DEC 解密过程

    /// <summary>
    /// DEC 解密过程
    /// </summary>
    /// <param name="EncValue">被解密的字符串</param>  
    /// <returns>返回被解密的字符串</returns>
    public static string Decrypt(string EncValue, string sKey)
    {
        if (sKey == null)
        {
            sKey = Key;
        }

        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = new byte[EncValue.Length / 2];
        for (int x = 0; x < EncValue.Length / 2; x++)
        {
            int i = (Convert.ToInt32(EncValue.Substring(x * 2, 2), 16));
            inputByteArray[x] = (byte)i;
        }

        des.Key = ASCIIEncoding.ASCII.GetBytes(sKey.Substring(0, 8));　//建立加密对象的密钥和偏移量，此值重要，不能修改
        des.IV = ASCIIEncoding.ASCII.GetBytes(sKey.Insert(0, "w").Substring(0, 8));
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();

        //建立StringBuild对象，createDecrypt使用的是流对象，必须把解密后的文本变成流对象
        StringBuilder ret = new StringBuilder();

        return System.Text.Encoding.Default.GetString(ms.ToArray());
    }
    #endregion

    #region 字符串截取
    public static string CutStr(string sInString, int iCutLength)
    {
        if (sInString == null || sInString.Length == 0 || iCutLength <= 0)
            return "";
        int iCount = System.Text.Encoding.GetEncoding("GBK").GetByteCount(sInString);
        if (iCount > iCutLength)
        {
            int iLength = 0;
            for (int i = 0; i < sInString.Length; i++)
            {
                int iCharLength = System.Text.Encoding.GetEncoding("GBK").GetByteCount(new char[] { sInString[i] });
                iLength += iCharLength;
                if (iLength == iCutLength)
                {
                    sInString = sInString.Substring(0, i + 1);
                    break;
                }
                else if (iLength > iCutLength)
                {
                    sInString = sInString.Substring(0, i);
                    break;
                }
            }
            sInString += "..";
        }
        return sInString;
    }
    #endregion

    #region 将字符串转换为html编码输出
    public static string ShowHtmlCutStr(string sInString, int iCutLength)
    {
        return HttpUtility.HtmlEncode(CutStr(sInString, iCutLength));
    }
    #endregion

    #region 去除HTML标记
    ///   <summary>   
    ///   去除HTML标记   
    ///   </summary>   
    ///   <param   name="NoHTML">包括HTML的源码   </param>   
    ///   <returns>已经去除后的文字</returns>   
    public static string NoHTML(string Htmlstring)
    {
        //删除脚本   
        Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //删除HTML   
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

        Htmlstring.Replace("<", "");
        Htmlstring.Replace(">", "");
        Htmlstring.Replace("\r\n", "");
        Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();


        return Htmlstring;
    }
    #endregion

    #region 过滤SQL字符
    /// <summary>
    /// 过滤 SQL 字符，防范 SQL 注入攻击
    /// </summary>
    /// <param name="str">要过滤的输入字符串</param>
    /// <returns></returns>
    public static string FiltrateSql(string str)
    {
        if (str == null || str.Length == 0)
            return "";
        string[] sql = "select,delete,update,from,count,max,top,where,set,order,'".Split(new char[] { ',' });
        str = str.Replace(" ", "　");
        str = str.Replace("*", "＊");
        for (int i = 0; i < sql.Length; i++)
        {
            str = str.ToLower().Replace(sql[i], " ");
        }
        return str;
    }
    #endregion

    #region 绑定下拉列表
    /// <summary>
    /// 绑定下拉列表
    /// </summary>
    /// <param name="ds">数据源</param>
    /// <param name="ddl">下拉列表</param>
    public static void BindDDLWays(DataSet ds, DropDownList ddl)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("—请选择—", "0"));
        if (CheckDataSet(ds))
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ListItem li = new ListItem();
                li.Text = dr["Title"].ToString();
                li.Value = dr["Id"].ToString();
                ddl.Items.Add(li);
            }
        }
    }
    /// <summary>
    /// 绑定下拉列表 没有加请选择这项
    /// </summary>
    /// <param name="ds">数据源</param>
    /// <param name="ddl">下拉列表</param>
    public static void BindDDLWays(DataSet ds, DropDownList ddl, int flag)
    {
        if (CheckDataSet(ds))
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ListItem li = new ListItem();
                li.Text = dr["Title"].ToString();
                li.Value = dr["Id"].ToString();
                ddl.Items.Add(li);
            }
        }
    }

    /// <summary>
    /// 绑定下拉列表 没有加请选择这项
    /// </summary>
    /// <param name="ds">数据源</param>
    /// <param name="ddl">下拉列表</param>
    /// <param name="ddl">指定下拉列表的Text字段</param>
    public static void BindDDLWays(DataSet ds, DropDownList ddl, string TextFiled)
    {
        if (CheckDataSet(ds))
        {
            ddl.Items.Insert(0, new ListItem("—请选择—", "0"));
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ListItem li = new ListItem();
                li.Text = dr[TextFiled].ToString();
                li.Value = dr["Id"].ToString();
                ddl.Items.Add(li);
            }
        }
    }
    /// <summary>
    /// 绑定下拉列表 没有加请选择这项
    /// </summary>
    /// <param name="ds">数据源</param>
    /// <param name="ddl">下拉列表</param>
    /// <param name="ddl">指定下拉列表的Text字段</param>
    public static void BindDDLWays(DataSet ds, DropDownList ddl, string TextFiled, string ValueFiled)
    {
        if (CheckDataSet(ds))
        {
            ddl.Items.Insert(0, new ListItem("—请选择—", "-1"));
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ListItem li = new ListItem();
                li.Text = dr[TextFiled].ToString();
                li.Value = dr[ValueFiled].ToString();
                ddl.Items.Add(li);
            }
        }
    }
    /// <summary>
    /// 绑定下拉框，0是两级,1是一级
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="ddl"></param>
    /// <param name="type">0|1</param>
    public static void BindDDLWaysTwo(DataSet ds, DropDownList ddl, int type)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("—请选择—", "-1"));
        if (CheckDataSet(ds))
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ListItem li = new ListItem();
                if (type == 0)
                {
                    if (dr["ParentId"].ToString() == "0")
                    {
                        li.Text = "—" + dr["Title"].ToString();
                        li.Value = dr["Id"].ToString();
                        ddl.Items.Add(li);
                        DataView dv = ds.Tables[0].DefaultView;
                        dv.RowFilter = "ParentId = " + dr["Id"].ToString();
                        dv.Sort = "Id desc";

                        if (dv != null && dv.Count > 0)
                        {
                            foreach (DataRowView drv in dv)
                            {
                                li = new ListItem();
                                li.Text = "——" + drv["Title"].ToString();
                                li.Value = drv["Id"].ToString();
                                ddl.Items.Add(li);
                            }
                        }
                    }
                }
                else
                {
                    if (dr["ParentId"].ToString() == "0")
                    {
                        li.Text = "—" + dr["Title"].ToString();
                        li.Value = dr["Id"].ToString();
                        ddl.Items.Add(li);
                    }
                }
            }
        }
    }

    /// <summary>
    /// 绑定下拉框，0是两级,1是一级
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="ddl"></param>
    /// <param name="type">0|1</param>
    public static void BindParentId(DataSet ds, DropDownList ddl, int type)
    {
        ddl.Items.Clear();
        ddl.Items.Add(new ListItem("顶级分类", "0"));
        if (CheckDataSet(ds))
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ListItem li = new ListItem();
                if (type == 0)
                {
                    if (dr["ParentId"].ToString() == "0")
                    {
                        li.Text = "—" + dr["Title"].ToString();
                        li.Value = dr["Id"].ToString();
                        ddl.Items.Add(li);
                        DataView dv = ds.Tables[0].DefaultView;
                        dv.RowFilter = "ParentId = " + dr["Id"].ToString();
                        dv.Sort = "Id desc";

                        if (dv != null && dv.Count > 0)
                        {
                            foreach (DataRowView drv in dv)
                            {
                                li = new ListItem();
                                li.Text = "——" + drv["Title"].ToString();
                                li.Value = drv["Id"].ToString();
                                ddl.Items.Add(li);
                            }
                        }
                    }
                }
                else
                {
                    if (dr["ParentId"].ToString() == "0")
                    {
                        li.Text = "—" + dr["Title"].ToString();
                        li.Value = dr["Id"].ToString();
                        ddl.Items.Add(li);
                    }
                }
            }
        }
    }

    #endregion

    #region 获取用户IP地址
    /// <summary>
    /// 获取用户IP地址
    /// </summary>
    /// <returns></returns>
    public static string GetIPAddress()
    {

        string user_IP = string.Empty;
        if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
        {
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                user_IP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                user_IP = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
        }
        else
        {
            user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        }
        return user_IP;
    }
    #endregion

    #region  根据ip地址判断其详细地址
    /// <summary>
    /// 读取yodao 接口IP地址
    /// </summary>
    public static string GetstringIpAddress()//strIP为IP
    {
        string strIP = GetIPAddress();
        string sURL = "http://www.youdao.com/smartresult-xml/search.s?type=ip&q=" + strIP + "";//youdao的URL
        string stringIpAddress = "";
        try
        {
            using (XmlReader read = XmlReader.Create(sURL))//获取youdao返回的xml格式文件内容
            {
                while (read.Read())
                {
                    switch (read.NodeType)
                    {
                        case XmlNodeType.Text://取xml格式文件当中的文本内容
                            if (string.Format("{0}", read.Value).ToString().Trim() != strIP)//youdao返回的xml格式文件内容一个是IP，另一个是IP地址，如果不是IP那么就是IP地址
                            {
                                stringIpAddress = string.Format("{0}", read.Value).ToString().Trim();//赋值
                            }
                            break;
                    }
                }
            }
        }
        catch (Exception)
        {
            stringIpAddress = "IP接口出错，未能获取数据";
        }

        return stringIpAddress;
    }
    #endregion  读取yodao 接口IP地址



    #region  保存图片文件

    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="path">文件夹路径</param>
    /// <param name="hpf">httpPositFile对象</param>
    /// <returns>返回值 返回文件名 正常 1 文件过大 2 格式不正确 正确格式.jpg .jpeg .gif .png .bmp</returns>
    public static string UpImage(string path, HttpPostedFile hpf)
    {
        //判断是否已上传文件
        if (hpf.ContentLength <= 0)
        {
            return string.Empty;
        }

        int FileLength = hpf.ContentLength;
        if (FileLength > 1024 * 10000)
        {
            return "1";//文件过大
        }
        string fileName = hpf.FileName.ToLower();

        if (!CheckIndexOfArray(fileName, ".jpg|.jpeg|.gif|.png|.bmp".ToLower().Split('|')))
        {
            return "2";//格式不正确 要输入正确的格式
        }


        string SaveName = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(0, 100000).ToString() + Path.GetExtension(fileName);

        hpf.SaveAs(HttpContext.Current.Server.MapPath(path + "/" + SaveName));

        return path + "/" + SaveName;

    }

    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="path">文件夹路径</param>
    /// <param name="hpf">httpPositFile对象</param>
    /// <returns>返回值 返回文件名 正常 1 文件过大 2 格式不正确 正确格式.jpg .jpeg .gif .png .bmp</returns>
    public static string UpImage(string path, HttpPostedFile hpf, string pathsave)
    {
        //判断是否已上传文件
        if (hpf.ContentLength <= 0)
        {
            return string.Empty;
        }

        int FileLength = hpf.ContentLength;
        if (FileLength > 1024 * 10000)
        {
            return "1";//文件过大
        }
        string fileName = hpf.FileName.ToLower();

        if (!CheckIndexOfArray(fileName, ".jpg|.jpeg|.gif|.png|.bmp".ToLower().Split('|')))
        {
            return "2";//格式不正确 要输入正确的格式
        }


        string SaveName = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(0, 100000).ToString() + Path.GetExtension(fileName);

        hpf.SaveAs(HttpContext.Current.Server.MapPath(path + "/" + SaveName));

        return pathsave + "/" + SaveName;

    }

    /// <summary>
    /// 判断字符串数组在Str中是否存在
    /// </summary>
    /// <param name="str">要判断的字符串</param>
    /// <param name="strarray">要判断的数组</param>
    /// <returns>不存在返回true 存在返回false</returns>
    public static bool CheckIndexOfArray(string str, string[] strarray)
    {
        bool b = false;
        foreach (string s in strarray)
        {
            if (str.IndexOf(s) > 0)
            {
                b = true;
                break;
            }
        }

        return b;

    }


    #endregion

    #region  保存文件

    /// <summary>
    /// 保存文件
    /// </summary>
    /// <param name="path">文件夹路径</param>
    /// <param name="hpf">httpPositFile对象</param>
    /// <returns>返回值 返回文件名 正常 1 文件过大 2 格式不正确 正确格式.doc|.docx|.rar|.pdf|.xls|.ppt</returns>
    public static string UpFile(string path, HttpPostedFile hpf)
    {
        //判断是否已上传文件
        if (hpf.ContentLength <= 0)
        {
            return string.Empty;
        }

        int FileLength = hpf.ContentLength;
        if (FileLength > 1024 * 10000)
        {
            return "1";//文件过大
        }
        string fileName = hpf.FileName.ToLower();

        if (!CheckIndexOfArray(fileName, ".doc|.docx|.rar|.pdf|.xls|.ppt".ToLower().Split('|')))
        {
            return "2";//格式不正确 要输入正确的格式
        }


        string SaveName = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(0, 100000).ToString() + Path.GetExtension(fileName);

        hpf.SaveAs(HttpContext.Current.Server.MapPath(path + "/" + SaveName));

        return path + "/" + SaveName;

    }

    #endregion

    #region 防止sql注入
    public static bool AntiSqlValid(string strSql)
    {
        string strValid = "'|;|or1=1|and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare";
        string[] strValids = strValid.Split('|');
        strSql = strSql.Replace(" ", "");//替换所有空格
        strSql = strSql.ToLower();//转为小写
        foreach (string strvali in strValids)
        {
            if (strSql.Contains(strvali))
            {
                return false;
            }
        }
        return true;
    }
    #endregion

    #region 验证dataset
    /// <summary>
    /// 验证dataset
    /// </summary>
    /// <param name="ds"></param>
    /// <returns></returns>
    public static bool CheckDataSet(DataSet ds)
    {
        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    #endregion

    #region 利用NPOI组件导入，导出Excel文件

    /// <summary>
    /// 将DataTable转成Xls文件导出
    /// </summary>
    /// <param name="page"></param>
    /// <param name="dt"></param>
    /// <param name="FileName"></param>
    /// <returns></returns>
    static public void ExportExcelByNPOI(Page page, DataTable dt, string FileName)
    {
        page.Response.ContentType = "application/vnd.ms-excel";
        page.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", FileName + ".xls"));
        page.Response.Clear();

        HSSFWorkbook hssfworkbook = new HSSFWorkbook();

        //设定文件相关信息
        DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
        dsi.Company = "SeeBio";
        hssfworkbook.DocumentSummaryInformation = dsi;
        SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
        si.Subject = "SeeBio";
        hssfworkbook.SummaryInformation = si;

        //将DataTable数据写入
        Sheet sheet1 = hssfworkbook.CreateSheet("SeeBio_ProductData");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            //创建行
            Row row = sheet1.CreateRow(i);
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                //创建单元格
                row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
            }
        }

        MemoryStream file = new MemoryStream();
        hssfworkbook.Write(file);

        page.Response.BinaryWrite(file.GetBuffer());
        page.Response.End();
    }


    /// <summary>
    /// 将Excel转成DataTable
    /// </summary>
    /// <param name="fileupload">上传控件实例引用</param>
    /// <returns></returns>
    static public DataTable ImportExcelByNPOI(FileUpload fileupload)
    {
        DataTable dt = new DataTable();
        using (FileStream file = new FileStream(fileupload.PostedFile.FileName, FileMode.Open, FileAccess.Read))
        {
            HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
            HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            //将Excel内数据读取到DataTable 中
            while (rows.MoveNext())
            {
                HSSFRow row = (HSSFRow)rows.Current;
                DataRow dr = dt.NewRow();

                for (int i = 0; i < row.LastCellNum; i++)
                {
                    HSSFCell cell = (HSSFCell)row.GetCell(i);
                    if (cell == null)
                    {
                        dr[i] = null;
                    }
                    else
                    {
                        dr[i] = cell.ToString();
                    }
                }
                dt.Rows.Add(dr);
            }
        }
        return dt;
    }

    #endregion

    #region 利用Sqlbulkcopy批量插入数据

    /// <summary>
    /// 利用Sqlbulkcopy批量插入数据
    /// </summary>
    /// <param name="dt">用于存放待插入数据的DataTable</param>
    /// <param name="InserTargetTable">要插入的表名</param>
    /// <param name="ColumnNameArr">对应表里数据列列名（将按照DataTable中的列顺序，插入到此数组对应顺序的字段当中）</param>
    static public void BatchInsertData(DataTable dt, string InserTargetTable, string[] ColumnNameArr)
    {
        SqlConnection sqlcon = new SqlConnection("server=192.168.1.9;uid=testuser;pwd=testuser;database=XB_Data");
        using (SqlBulkCopy sqlBc = new SqlBulkCopy(sqlcon))
        {
            sqlBc.DestinationTableName = InserTargetTable;
            sqlBc.BatchSize = 300;
            sqlBc.BulkCopyTimeout = 60 * 3;
        }
    }

    #endregion

    #region 计算两个字符串数组之间交集或差集
    /// <summary>
    /// 计算两个数组之间交集或差集
    /// </summary>
    /// <param name="arrA">数组A</param>
    /// <param name="arrB">数组B</param>
    /// <param name="IntersectionOrExcept">要返回交集还是差集（0：交集，1：差集）</param>
    /// <returns>返回数组中是数组A里的元素</returns>
    static public string[] ReturnIntersectionOrExcept(string[] arrA, string[] arrB, int IntersectionOrExcept)
    {
        ArrayList arrC = new ArrayList();
        bool Flag = false;//是否相等标识
        if (arrA.Length > 0)
        {
            if (IntersectionOrExcept == 0)//交集
            {
                for (int i = 0; i < arrA.Length; i++)
                {
                    for (int j = 0; j < arrB.Length; j++)
                    {
                        if (arrA[i] == arrB[j])
                        {
                            arrC.Add(arrA[i]);
                            break;
                        }
                    }
                }
            }
            else if (IntersectionOrExcept == 1)//差集
            {
                for (int i = 0; i < arrA.Length; i++)
                {
                    for (int j = 0; j < arrB.Length; j++)
                    {
                        if (arrA[i] == arrB[j])
                        {
                            Flag = true;
                            break;
                        }
                        else
                        {
                            Flag = false;
                        }
                    }
                    if (!Flag)
                    {
                        arrC.Add(arrA[i]);
                    }
                }
            }
        }

        return (string[])arrC.ToArray(typeof(String));
    }
    #endregion

    #region 将对应数字转换成字母（如1--A，2--B）

    /// <summary>
    /// 将对应数字转换成字母（如1--A，2--B）
    /// </summary>
    /// <returns></returns>
    public static char ConvertASCII(int ASCII)
    {
        return Convert.ToChar(ASCII + 64);
    }

    #endregion

    #region 过滤页面上TextBox以及TextArea的特殊字符
    /// <summary>
    /// 过滤页面上TextBox以及TextArea的特殊字符
    /// </summary>
    /// <param name="page"></param>
    /// <returns></returns>
    public static Page FilterSpecial(Page page)
    {
        foreach (Control con in page.Form.Controls)
        {
            if (con.GetType().ToString() == "System.Web.UI.WebControls.TextBox") //过滤Textbox
            {
                TextBox textbox = con as TextBox;
                textbox.Text = textbox.Text.Trim().Replace("'", "''");
            }
            else if (con.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlTextArea")//过滤Textarea
            {
                HtmlTextArea textarea = con as HtmlTextArea;
                textarea.Value = textarea.Value.Trim().Replace("'", "''");
            }
        }
        return page;
    }

    #endregion

    #region 返回红色字体HTML以"<font color=\"red\"></font>"标签包裹
    /// <summary>
    /// 返回红色字体HTML以"<font color=\"red\"></font>"标签包裹
    /// </summary>
    ///<param name="text">要显示的文本</param>
    /// <returns></returns>
    public static string RedFont(string text)
    {
        return "<font color=\"red\">" + text + "</font>";
    }
    #endregion

    #region 验证Url查询字符串(QueryString)是否为数字
    /// <summary>
    /// 验证Url查询字符串是否合法
    /// </summary>
    /// <param name="page">page</param>
    /// <param name="strList">QueryString键名数组：如Url为"news.aspx?Id=1&News=123" 则传值为string str[]{"Id","News"}</param>
    /// <param name="locationhref">验证不通过时要跳转到的Url</param>
    public static bool ValidateQueryString(Page page, string[] strList, string locationhref)
    {
        //验证是否通过标识
        bool flag = true;
        string QueryString = string.Empty;
        Regex reg = new Regex("^[0-9]+$");

        //循环判断查询字符串是否通过验证
        foreach (string str in strList)
        {
            if (!string.IsNullOrEmpty(page.Request.QueryString[str]))
            {
                QueryString = page.Request.QueryString[str] as string;

                //判断是否为数字
                if (!reg.IsMatch(QueryString))
                {
                    if (!string.IsNullOrEmpty(locationhref))
                    {
                        page.Response.Write("<script>location.href='" + locationhref + "';</script>");
                    }
                    flag = false;
                    break;
                }
            }
            else
            {
                flag = false;
            }
        }
        return flag;
    }

    /// <summary>
    /// 验证Url查询字符串是否合法
    /// </summary>
    /// <param name="page">page</param>
    /// <param name="strList">QueryString键名</param>
    /// <param name="locationhref">验证不通过时要跳转到的Url,可为null</param>
    public static bool ValidateQueryString(Page page, string key, string locationhref)
    {
        return ValidateQueryString(page, new string[] { key }, locationhref);
    }
    #endregion

    #region ErpPwd加密
    /// <summary>
    /// ErpPwd加密
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    static public string ErpPwdEncrypt(string text)
    {
        return ErpPwd.Encrypt.EncryptOrDencrypt(text, true);
    }

    #endregion

    #region ErpPwd解密
    /// <summary>
    /// ErpPwd解密
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    static public string ErpPwdDeEncrypt(string text)
    {
        return ErpPwd.Encrypt.EncryptOrDencrypt(text, false);
    }

    #endregion


    #region qiupl
    /// <summary>
    /// 截取字符串
    /// </summary>
    /// <param name="str">字符串</param>
    /// <param name="len">要截取的长度</param>
    /// <returns></returns>
    public string cutStr(string str, int len)
    {
        if (str != "")
        {
            str = str.Length > len ? str.Substring(0, len) : str;
        }
        return str;
    }

    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <param name="to">接受者邮箱地址</param>
    /// <param name="from">发送者邮箱地址</param>
    /// <param name="subject">标题</param>
    /// <param name="body">内容</param>
    /// <param name="userName">用户</param>
    /// <param name="password">密码</param>
    /// <param name="smtpHost"></param>
    static public void Send(string to, string from, string subject, string body, string userName, string password, string smtpHost)
    {
        //事例
        //string strHtml = "fasldkfjsld";
        //NetMail.Send("发送标题", "mmm@163.com", "平方空间", strHtml, "pl", "pm", "smtp.163.com");
        try
        {

            MailMessage message = new MailMessage(from, to);
            message.Subject = subject;//设置邮件主题    
            message.IsBodyHtml = true;//设置邮件正文为html格式    
            message.Body = body;//设置邮件内容    
            SmtpClient client = new SmtpClient(smtpHost);
            //设置发送邮件身份验证方式    
            //注意如果发件人地址是abc@def.com，则用户名是abc而不是abc@def.com    
            client.Credentials = new NetworkCredential(userName, password);
            client.Send(message);

        }
        catch
        {

        }
    }
    #endregion

}

